// Learn cc.Class:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {
        JoystickIn: {
            default: null,
            type: cc.Node,
            displayName: "Inner Joystick",
        },
        Player:{
            default:null,
            type:cc.Node,
        }
    },

    // LIFE-CYCLE CALLBACKS

    onLoad() {
        this.node.on(cc.Node.EventType.TOUCH_START, function (event) {
            this.touchStart(event);
        }, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, function (event) {
            this.touchStart(event);
        }, this);
        this.node.on(cc.Node.EventType.TOUCH_END, function (event) {
            this.cancel(event);
        }, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, function (event) {
            this.cancel(event);
        }, this);
    },
    touchStart: function (event) {
        var x = event.getLocationX()+Math.abs(this.node.x)-this.node.parent.width/2;
        var y = event.getLocationY()+Math.abs(this.node.y)-this.node.parent.height/2;
        if(Math.sqrt(x*x+y*y)>=60){
            x=x*(60/Math.sqrt(x*x+y*y));
            y=y*(60/Math.sqrt(x*x+y*y));
        }
        this.JoystickIn.x=x;
        this.JoystickIn.y=y;
        // var move = cc.moveTo(0.2, cc.v2(x, y));
        // this.JoystickIn.runAction(move);
        this.Player.getComponent("Player").move = true;
        this.Player.getComponent("Player").moveX = this.Player.getComponent("Player").speed*(x/Math.sqrt(x*x+y*y));
        this.Player.getComponent("Player").moveY = this.Player.getComponent("Player").speed*(y/Math.sqrt(x*x+y*y));
    },
    cancel:function(event){
        this.Player.getComponent("Player").move = false;
        this.JoystickIn.x=0;
        this.JoystickIn.y=0;
    },

    start() {

    },

    // update (dt) {},
});
